from flask import Flask, render_template, request, jsonify, session, redirect, url_for
from datetime import datetime
import traceback
from backend.nlp.synonym_engine import SynonymEngine
from backend.services import chat_service, order_service, product_service
from backend.services.order_service import OrderService
from backend.services.product_service import ProductService
from backend.services.address_service import AddressService
from backend.services.chat_service import ChatService
from backend.services.after_sales_service import AfterSalesService
from backend.nlp.intent_recognizer import IntentRecognizer
from backend.nlp.xunfei_api import XunfeiLLM
from backend.utils.db import get_db_connection
from backend.config import SECRET_KEY, DEBUG
from flask_cors import CORS
# 可以在单独的脚本中运行或直接在app.py中临时添加
from backend.nlp.intent_trainer import IntentTrainer
trainer = IntentTrainer()
trainer.train_model()
# recognizer = IntentRecognizer()
# result = recognizer.recognize_intent("P001多少钱")
# print(result)  # 应该返回product_query意图
# 初始化Flask应用
app = Flask(__name__,
            static_folder='../frontend/static',  # 静态文件目录
            template_folder='../frontend/templates')  # 模板文件目录
CORS(app)  # 允许跨域请求

app.secret_key = SECRET_KEY
# app.config['SESSION_COOKIE_SECURE'] = True  # 生产环境中启用
app.debug = DEBUG

# 初始化意图识别器
intent_recognizer = IntentRecognizer()

# 正确初始化讯飞API类
xunfei_api = XunfeiLLM()

# 初始化同义词引擎
synonym_engine = SynonymEngine()

def verify_user(user_id, password):
    """验证用户登录信息"""
    try:
        with get_db_connection() as (cursor, connection):
            sql = "SELECT user_id, password, user_type FROM users WHERE user_id = %s"
            cursor.execute(sql, (user_id,))
            user = cursor.fetchone()

            if user:
                # 用户存在，检查密码
                if user['password'] == password:
                    return user
                else:
                    print("密码错误")
            else:
                print(f"用户不存在: {user_id}")

        return None
    except Exception as e:
        print(f"数据库查询失败：{e}")
        return None

def register_user(user_id, password, user_type='user'):
    """注册新用户"""
    try:
        with get_db_connection() as (cursor, conn):
            # 检查用户ID是否已存在
            sql_check = "SELECT * FROM users WHERE user_id = %s"
            cursor.execute(sql_check, (user_id,))
            if cursor.fetchone():
                return False, "用户ID已存在"
            sql_insert = "INSERT INTO users (user_id, password, user_type, created_at) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql_insert, (user_id, password, user_type, datetime.now()))
            conn.commit()
            return True, "注册成功"
    except Exception as e:
        print(f"数据库查询失败：{e}")
        return False, f"注册失败：{e}"

# 路由定义
@app.route('/')
def index():
    """首页，重定向到登录页"""
    if 'user_id' in session:
        return redirect(url_for('chat'))
    return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    if request.method == 'POST':
        # 区分表单提交和JSON提交（前端存在两种提交方式，需统一处理）
        if request.content_type == 'application/json':
            data = request.get_json()
            user_id = data.get('user_id')
            password = data.get('password')
        else:
            user_id = request.form.get('user_id')
            password = request.form.get('password')

        # 添加调试信息
        print(f"收到登录请求 - 用户ID: {user_id}, 密码: {password}")
        print(f"请求类型: {request.content_type}")

        user = verify_user(user_id, password)
        if user:
            session['user_id'] = user['user_id']
            session['user_type'] = user['user_type']

            if user['user_type'] == 'admin':
                return jsonify({"success": True, "redirect": url_for('admin')})
            else:
                return jsonify({"success": True, "redirect": url_for('chat')})
        else:
            return jsonify({"success": False, "message": "用户名或密码错误"})

    # 如果已登录，重定向到相应页面
    if 'user_id' in session:
        if session['user_type'] == 'admin':
            return redirect(url_for('admin'))
        else:
            return redirect(url_for('chat'))
    return render_template('login.html')

@app.route('/register', methods=['POST'])
def register():
    """用户注册"""
    if request.content_type == 'application/json':
        data = request.get_json()
        user_id = data.get('user_id')
        password = data.get('password')
    else:
        user_id = request.form.get('user_id')
        password = request.form.get('password')

    success, message = register_user(user_id, password)
    return jsonify({"success": success, "message": message})

@app.route('/logout')
def logout():
    """退出登录"""
    # 清除用户认证信息
    session.clear()  # 或者删除特定的认证字段
    # 重定向到登录页面
    return redirect(url_for('login'))  # 确保路径正确

@app.route('/chat')
def chat():
    """用户聊天页面"""
    if 'user_id' not in session or session['user_type'] != 'user':
        return redirect(url_for('login'))

    return render_template('chat.html')

@app.route('/admin')
def admin():
    """管理员页面"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return redirect(url_for('login'))

    return render_template('admin.html')

def call_xunfei_api(prompt, history=[]):
    """调用讯飞星火API获取回复 """
    try:
        llm = XunfeiLLM()
        messages = history + [{"role": "user", "content": prompt}]
        response = llm.get_answer(messages)
        return response if response else "抱歉，暂时无法回答您的问题"
    except Exception as e:
        print(f"调用讯飞API失败: {e}")
        return "服务暂时不可用，请稍后再试"

# 新增API：获取所有用户
@app.route('/api/admin/get_all_users')
def admin_get_all_users():
    """管理员获取所有用户"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    try:
        with get_db_connection() as (cursor, conn):
            sql = "SELECT user_id, username FROM users WHERE user_type = 'user' "
            cursor.execute(sql)
            users = cursor.fetchall()
            return jsonify({"success": True, "users": users})
    except Exception as e:
        print(f"获取用户列表失败: {e}")
        return jsonify({"success": False, "message": "获取用户列表失败"})
    finally:
        print()


# 管理员发送消息
@app.route('/api/admin/send_message', methods=['POST'])
def admin_send_message():
    """管理员发送消息"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    data = request.json
    user_id = data.get('user_id')
    message = data.get('message')

    if not user_id or not message:
        return jsonify({"success": False, "message": "参数错误"})

    # 保存管理员消息
    chat_service = ChatService()
    chat_service.save_message(
        user_id=user_id,
        message=message,
        sender_type="admin"  # 标记为管理员消息
    )

    return jsonify({"success": True})


# 修改获取聊天历史的API
@app.route('/api/get_chat_history')
def get_chat_history():
    """获取用户聊天历史记录"""
    user_id = request.args.get('user_id')
    sender_type = request.args.get('sender_type')  # 新增sender_type参数

    if not user_id:
        if 'user_id' not in session:
            return jsonify({"success": False, "message": "未登录"})
        user_id = session['user_id']

    chat_service = ChatService()

    # 根据sender_type参数过滤记录
    if sender_type:
        history = chat_service.get_chat_history_by_sender(user_id, sender_type)
    else:
        history = chat_service.get_chat_history(user_id)

    return jsonify({"success": True, "history": history})


# 在原有的send_message路由中完善处理逻辑
@app.route('/api/send_message', methods=['POST'])
def send_message():
    try:  # 外层捕获整个请求的异常
        if 'user_id' not in session:
            return jsonify({"success": False, "message": "未登录"})

        user_id = session.get('user_id')
        message = request.json.get('message', '').strip()

        # 保存用户消息到数据库（可能失败，需捕获）
        chat_service = ChatService()
        if not chat_service.save_message(user_id=user_id, message=message, sender_type="user"):
            return jsonify({"success": False, "message": "消息保存失败"})

        # 意图识别流程（可能涉及NLP模型加载/调用异常）
        try:
            intent_result = intent_recognizer.recognize_intent(message, user_id, session.get('context', {}))
        except Exception as e:
            print(f"意图识别失败: {e}")
            return jsonify({"success": False, "message": "系统处理消息失败，请重试"})

        intent_type = intent_result['intent_type']
        entities = intent_result['entities']
        standardized_text = intent_result['standardized_text']

        response = ""
        # 实体缺失处理（涉及产品/订单查询，可能有数据库异常）
        if not any(entities.values()):
            try:
                products = ProductService().fuzzy_search_products(standardized_text)
                orders = OrderService().fuzzy_search_orders(user_id, standardized_text)
            except Exception as e:
                print(f"模糊查询失败: {e}")
                response = "查询服务暂时不可用，请稍后再试"
            else:
                # 正常处理模糊查询结果
                if products:
                    product_names = [p['name'] for p in products[:3]]
                    response = f"您是否想查询以下产品？\n{', '.join(product_names)}\n请确认产品名称或提供更多信息。"
                elif orders:
                    order_ids = [o['order_id'] for o in orders[:3]]
                    response = f"您是否想查询以下订单？\n{', '.join(order_ids)}\n请确认订单号或提供更多信息。"
                else:
                    response = "请提供更多关于产品、订单或服务的信息，以便我更好地为您服务。"
        else:
            # 调用意图处理器（可能涉及数据库/API操作）
            try:
                response = intent_recognizer.handle_intent(intent_type, entities, standardized_text, user_id)
            except Exception as e:
                print(f"意图处理失败: {e}")
                response = "处理您的请求时出现错误，请稍后重试"

        # 保存系统回复到数据库（可能失败）
        if not chat_service.save_message(user_id=user_id, message=response, sender_type="assistant"):
            print("系统回复保存失败")  # 不阻断流程，但记录错误

        # 更新会话上下文
        session['context'] = {
            "last_intent": intent_type,
            "last_entities": entities,
            "last_response": response
        }
        return jsonify({
            "success": True,
            "response": response,
            "intent": intent_type,
            "entities": entities
        })
    except Exception as e:
        error_msg = f"请求处理异常: {str(e)}"
        print(f"{error_msg}\n{traceback.format_exc()}")  # 打印完整堆栈
        chat_service.save_message(user_id=user_id, message="系统出错了", sender_type="assistant")
        return jsonify({"success": False, "message": error_msg})

@app.route('/api/get_user_orders')
def get_user_orders():
    """获取用户订单"""
    if 'user_id' not in session:
        return jsonify({"success": False, "message": "未登录"})

    user_id = session['user_id']
    address_service = AddressService()
    orders = address_service.get_user_orders_with_address(user_id)

    return jsonify({"success": True, "orders": orders})

@app.route('/api/update_address', methods=['POST'])
def update_address():
    """更新收货地址"""
    if 'user_id' not in session:
        return jsonify({"success": False, "message": "未登录"})

    order_id = request.json.get('order_id')
    new_address = request.json.get('new_address')

    if not order_id or not new_address:
        return jsonify({"success": False, "message": "订单号和新地址不能为空"})

    address_service = AddressService()
    success, message = address_service.update_shipping_address(order_id, new_address)

    return jsonify({"success": success, "message": message})


@app.route('/api/apply_after_sales', methods=['POST'])
def apply_after_sales():
    """申请售后服务"""
    if 'user_id' not in session:
        return jsonify({"success": False, "message": "未登录"})

    order_id = request.json.get('order_id')
    reason = request.json.get('reason', '')

    if not order_id:
        return jsonify({"success": False, "message": "订单号不能为空"})

    after_sales_service = AfterSalesService()
    success, message = after_sales_service.create_after_sales_request(order_id, reason)

    return jsonify({"success": success, "message": message})


# 新增API：处理售后申请
@app.route('/api/process_after_sales', methods=['POST'])
def process_after_sales():
    """处理售后申请（同意或拒绝）"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    order_id = request.json.get('order_id')
    action = request.json.get('action')  # 'approve' 或 'reject'

    if not order_id or action not in ['approve', 'reject']:
        return jsonify({"success": False, "message": "参数错误"})

    after_sales_service = AfterSalesService()
    success, message = after_sales_service.process_after_sales_request(order_id, action)

    return jsonify({"success": success, "message": message})


# 修改管理员获取所有订单的API
@app.route('/api/admin/get_all_orders')
def admin_get_all_orders():
    """管理员获取所有订单"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    try:
        with get_db_connection() as (cursor, conn):
            sql = """
                  SELECT o.order_id,
                         o.user_id,
                         p.name        AS product_name,
                         o.quantity,
                         o.total_price AS total_amount,
                         o.status,
                         o.after_sales_status
                  FROM orders o
                           JOIN products p ON o.product_id = p.product_id
                  ORDER BY o.order_time DESC \
                  """
            cursor.execute(sql)
            orders = cursor.fetchall()

            # 转换状态显示
            for order in orders:
                if order['after_sales_status'] == 'applied':
                    order['display_status'] = '申请售后'
                elif order['after_sales_status'] == 'approved':
                    order['display_status'] = '售后中'
                else:
                    order['display_status'] = order['status']

            return jsonify({"success": True, "orders": orders})
    except Exception as e:
        print(f"获取订单失败: {e}")
        return jsonify({"success": False, "message": "获取订单失败"})


@app.route('/api/admin/get_pending_chat_requests')
def get_pending_chat_requests():
    """获取待处理的人工聊天请求"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    chat_service = ChatService()
    requests = chat_service.get_pending_human_chat_requests()

    return jsonify({"success": True, "requests": requests})

@app.route('/api/admin/accept_chat_request/<int:request_id>')
def accept_chat_request(request_id):
    """接受人工聊天请求"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    admin_id = session['user_id']
    chat_service = ChatService()
    user_id = chat_service.accept_human_chat_request(request_id, admin_id)

    if user_id:
        return jsonify({"success": True, "user_id": user_id})
    else:
        return jsonify({"success": False, "message": "无法接受请求"})

# 产品管理API
@app.route('/api/admin/products', methods=['GET', 'POST'])
def admin_products():
    """产品管理接口"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    product_service = ProductService()
    try:
        if request.method == 'GET':
            # 获取所有产品
            products = product_service.get_all_products()
            return jsonify({"success": True, "products": products})
        elif request.method == 'POST':
            # 添加新产品
            product_data = request.json
            product_id = product_service.add_product(product_data)
            if product_id:
                return jsonify({"success": True, "product_id": product_id})
            else:
                return jsonify({"success": False, "message": "添加产品失败"})
    except Exception as e:
        print(f"产品管理错误: {str(e)}")
        return jsonify({"success": False, "message": f"操作失败: {str(e)}"})


# 获取单个产品详情
@app.route('/api/admin/products/<int:product_id>')
def get_product_detail(product_id):
    """获取单个产品详情"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    try:
        product_service = ProductService()
        product = product_service.get_product_by_id(product_id)
        if product:
            return jsonify({"success": True, "product": product})
        else:
            return jsonify({"success": False, "message": "产品不存在"})
    except Exception as e:
        print(f"获取产品详情失败: {str(e)}")
        return jsonify({"success": False, "message": "获取产品详情失败"})


# 删除产品
@app.route('/api/admin/products/<int:product_id>', methods=['DELETE'])
def delete_product(product_id):
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    try:
        product_service = ProductService()
        success = product_service.delete_product(product_id)
        if success:
            return jsonify({"success": True})
        else:
            return jsonify({"success": False, "message": "删除产品失败"})
    except Exception as e:
        print(f"删除产品失败: {str(e)}")
        return jsonify({"success": False, "message": "删除产品失败"})


# 产品知识库接口
@app.route('/api/admin/product-knowledge', methods=['GET', 'POST', 'PUT', 'DELETE'])
def admin_product_knowledge():
    """产品知识库管理接口"""
    if 'user_id' not in session or session['user_type'] != 'admin':
        return jsonify({"success": False, "message": "权限不足"})

    product_service = ProductService()
    try:
        if request.method == 'GET':
            # 获取所有产品知识
            knowledge = product_service.get_product_knowledge()
            return jsonify({"success": True, "knowledge": knowledge})

        elif request.method == 'POST':
            # 添加产品知识
            knowledge_data = request.json
            with get_db_connection() as (cursor, conn):
                sql = """
                      INSERT INTO product_knowledge
                          (product_id, ingredients, usage_instructions, effect, skin_type)
                      VALUES (%s, %s, %s, %s, %s)
                      """
                cursor.execute(sql, (
                    knowledge_data['product_id'],
                    knowledge_data['ingredients'],
                    knowledge_data['usage_instructions'],
                    knowledge_data['effect'],
                    knowledge_data['skin_type']
                ))
                conn.commit()
            return jsonify({"success": True, "message": "添加成功"})

        elif request.method == 'PUT':
            # 更新产品知识
            knowledge_data = request.json
            with get_db_connection() as (cursor, conn):
                sql = """
                      UPDATE product_knowledge
                      SET ingredients        = %s,
                          usage_instructions = %s,
                          effect             = %s,
                          skin_type          = %s
                      WHERE product_id = %s
                      """
                cursor.execute(sql, (
                    knowledge_data['ingredients'],
                    knowledge_data['usage_instructions'],
                    knowledge_data['effect'],
                    knowledge_data['skin_type'],
                    knowledge_data['product_id']
                ))
                conn.commit()
            return jsonify({"success": True, "message": "更新成功"})

        elif request.method == 'DELETE':
            # 删除产品知识
            product_id = request.args.get('product_id')
            with get_db_connection() as (cursor, conn):
                sql = "DELETE FROM product_knowledge WHERE product_id = %s"
                cursor.execute(sql, (product_id,))
                conn.commit()
            return jsonify({"success": True, "message": "删除成功"})

    except Exception as e:
        print(f"产品知识库错误: {str(e)}")
        return jsonify({"success": False, "message": f"操作失败: {str(e)}"})


@app.route('/api/admin/product-knowledge', methods=['GET'])
def get_product_knowledge_detail():
    product_id = request.args.get('product_id')
    if not product_id:
        return jsonify({"success": False, "message": "缺少产品ID"})

    product_service = ProductService()
    knowledge = product_service.get_product_knowledge_by_id(product_id)
    return jsonify({"success": True, "knowledge": knowledge})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)